package com.taotao.job.core.runresult;

import com.taotao.job.core.enums.JobType;
import com.taotao.job.core.enums.RunStatus;
import com.taotao.job.core.executor.RunResult;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author fanbeibei
 * @version 1.0
 * @date 2021/2/4 15:39
 */
@Slf4j
public abstract class AbstractRunResultProccessor implements RunResultProccessor {

    @Override
    public void proccessRunResult(RunResult runResult) {


        Integer runStatus = null;
        if (RunStatus.isLastRunStatus(runStatus)) {

            return;
        }


        boolean updateRunStatusSuccess = false;
        JobType jobType = JobType.getByCode(runResult.getExecutorContext().getJobType());
        switch (jobType) {
            case WORK_FLOW:
                // 若果是工作流任务则获取所有下级的运行实例，判断更新运行状态
                break;
            case NOMAL:


                break;
            case WORK_FLOW_NODE:
                // 若果是工作流任务则更新状态，并则触发工作流任务的proccessRunInfo()方法
                break;
            default:
                log.error("error jobType!!runInfo={}", runResult);
        }


        if (updateRunStatusSuccess && Objects.equals(runResult.getRunStatus(), RunStatus.SUCCESS.getCode())) {
            triggerPostJob(runResult.getExecutorContext().getJobId(), runResult.getExecutorContext().getJobInstanceId());
        }

    }


    /**
     * 更新实例运行状态
     *
     * @param jobInstanceId
     * @param preRunStatus
     * @param newRunStatus
     * @return
     */
    private boolean updateRunStatus(Long jobInstanceId, Integer preRunStatus, Integer newRunStatus) {

        if (Objects.equals(preRunStatus, newRunStatus)) {
            return false;
        }


        if (Objects.equals(newRunStatus, RunStatus.SUCCESS.getCode())) {
            //更新触发状态，防止触发成功但调度器没有收到回应

        }

        return false;
    }


    /**
     * 拉起下级任务
     *
     * @param jobId
     * @param jobInstanceId
     */
    public void triggerPostJob(Long jobId, Long jobInstanceId) {
        //TODO
        // 1. 获取下级任务

        //2. 拉起所有的下级任务

    }

}
